<template>
  <el-card>
    <div slot="header">
      <h3>删除销售区域</h3>
    </div>
    <div v-loading="pageLoading">
      <div class="delete-area-wrap">
        <text-tooltip max-width="400px" :textContent="salesArea.names">
          <h4 slot="content-label">删除区域：</h4>
        </text-tooltip>
        <el-button
          v-if="showBtn('选择区域')"
          type="text"
          size="large"
          @click="handleSelectArea"
        >选择区域
        </el-button>
      </div>
      <!-- 发起原因输入框 -->
      <LaunchReasonInput required :reason.sync="launchReason" />
      <el-row>
        <skus-table
          ref="skusTable"
          :defaultMinWidth="100"
          :tableHeight="480"
          :dataSource="TableInfo.list"
          :columns="TableInfo.columns"
          :loading="TableInfo.loading"
          :actionRender="renderTableBtnAction"
        >
          <!-- 按钮操作栏 -->
          <BtnRender slot="content_context" :render="renderBtnsBar" />
        </skus-table>
      </el-row>
    </div>
    <SalesAreaDialog
      :visible.sync="salesArea.visible"
      :cityList="salesArea.list"
      :selectCitys="salesArea.codes"
      @getSaleAreas="updateSaleAreaInfo"
    />
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="updateTableListBySeniorLinked"
    />
    <AssociateGoodsDialog
      ref="associateRef"
      :visible.sync="dialogVisible"
      @getResults="updateTableListByAssociateGoods"
    />
  </el-card>
</template>
<script>
import { mapGetters } from 'vuex';
import LaunchReasonInput from '@/components/LaunchReasonInput';
import TextTooltip from '@/components/ShowContent/TextTooltip';
import SalesAreaDialog from '@/components/SalesAreaDialog';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import AssociateGoodsDialog from '../components/AssociateGoodsDialog';
import { TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { setAuthBtnId, createExcelByExport, generateUuid } from '@/utils/bizUtils';
import { TABLE_COLUMNS, ERROR_MSG_COL } from './constants';
import {
  queryLoginUserSaleAreaService,
  queryBusinessAreaListService
} from '@/api/public';
import {
  querySkuList4DelSaleAreaService,
  commitDelSaleAreaService,
  exportValidErrorRowListService
} from '@/api/commodity/commodityInfoEdit/saleAreaDelete';
export default {
  components: {
    TextTooltip,
    SalesAreaDialog,
    SkusTable,
    BtnRender,
    SeniorLinkedDialog,
    AssociateGoodsDialog,
    LaunchReasonInput
  },
  data () {
    return {
      launchReason: '', // 发起原因
      pageLoading: false,
      salesArea: {
        visible: false,
        names: '',
        codes: [],
        list: [],
      },
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS, dimensionKey: 'skuNo' }),
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }],
      },
      btnLoading: {
        exportAbnormal: false, // 导出异常数据loading
        submit: false, // 提交loading
      },
      dialogVisible: false, // 关联商品弹框开关
      skuNos: [], // 已关联商品编码集合
    }
  },
  created () {
    this.setAreaInfo()
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    // 没有异常数据
    hasNoErrMsgs () {
      const hasNoErrMsgs = this.TableInfo.list.every(item => !item.errorMsg)
      return hasNoErrMsgs
    },
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnBars = [
        {
          label: '导出异常数据',
          method: this.handleExportAbnormalData,
          loading: this.btnLoading.exportAbnormal,
          disabled: this.hasNoErrMsgs
        },
        {
          label: '一键清除异常数据',
          method: this.handleClearAbnormalData,
          disabled: this.hasNoErrMsgs
        },
        {
          label: '高级关联',
          method: this.handleSeniorAssociate,
          hasAuth: true
        },
        {
          label: '关联商品',
          method: this.handleAssociateGoods,
          hasAuth: true
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.btnLoading.submit,
          disabled: this.TableInfo.isNullList(),
          hasAuth: true
        }
      ]
      return getListPageBtnsBar(h, btnBars, this.showBtn)
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '库存详情', method: this.handleViewStockDetails },
        { label: '删除', method: this.handleDeleteSku }
      ]
      return getTableAction({ h, row, actionList })
    },
    // 选择销售区域
    handleSelectArea () {
      this.salesArea.visible = true
    },
    // 获取销售区域集合
    async getSaleAreaList () {
      const res = await queryBusinessAreaListService()
      return res?.retData ?? []
    },
    // 获取当前登录人销售区域信息
    async getCurLogonAreaInfo () {
      const res = await queryLoginUserSaleAreaService()
      return res?.retData ?? {}
    },
    // 设置销售区域信息
    async setAreaInfo () {
      try {
        this.pageLoading = true
        const [result1, result2] = await Promise.allSettled([this.getSaleAreaList(), this.getCurLogonAreaInfo()])
        this.pageLoading = false
        this.salesArea.list = result1.status == 'fulfilled' ? result1.value : [] // 设置销售区域集合
        // 设置登录人销售区域信息
        const logonInfo = result2.status == 'fulfilled' ? result2.value : {}
        this.salesArea.names = logonInfo?.shortName
        this.salesArea.codes = logonInfo?.areaCode ? [logonInfo.areaCode] : []
      } catch (err) {
        this.pageLoading = false
      }
    },
    // 更新销售区域信息
    updateSaleAreaInfo (areaCodes) {
      this.salesArea.names = this.salesArea.list
        .filter(item => areaCodes.includes(item.areaCode))
        .map(item => item.shortName)
        .join('')
      this.salesArea.codes = areaCodes
      if (this.TableInfo.isNullList()) return // 表格为空时不需要刷新数据
      this.setTableList()
    },
    // 导出异常数据
    async handleExportAbnormalData () {
      const errorData = this.TableInfo.list.filter(item => item.errorMsg)
      const data = errorData
      const loadingFn = state => { this.btnLoading.exportAbnormal = state }
      const res = await exportValidErrorRowListService(data, loadingFn)
      createExcelByExport({ excelTitle: `删除销售区域异常数据_${generateUuid()}`, res })
    },
    // 一键清除异常数据
    handleClearAbnormalData () {
      this.TableInfo.setList(this.TableInfo.list.filter(item => !item.errorMsg))
    },
    // 高级关联
    handleSeniorAssociate () {
      setAuthBtnId('高级关联')
      this.seniorLinked.visible = true
    },
    // 关联商品
    handleAssociateGoods () {
      setAuthBtnId('关联商品')
      this.dialogVisible = true
    },
    // 提交
    handleSubmit () {
      if (!this.launchReason) return this.$message.warning('发起原因不能为空')
      this.TableInfo.setColumns(TABLE_COLUMNS) // 重置表列
      this.submitDeleteAreaInfo()
    },
    // 库存详情
    handleViewStockDetails (row) {
      const { href } = this.$router.resolve({
        name: 'stopOrEnableManageToHandle',
        query: { spuNo: row.spuNo }
      })
      window.open(href, '_blank')
    },
    // 删除对应SKU
    handleDeleteSku (row) {
      this.TableInfo.removeList(row)
    },
    // 高级查询更新表格数据
    updateTableListBySeniorLinked (skuNos) {
      this.setTableList([...new Set(skuNos)])
    },
    // 关联商品更新表格数据
    updateTableListByAssociateGoods (results) {
      const skuNos = results.map(row => row.skuNo)
      this.setTableList([...new Set(skuNos)])
    },
    // 设置表格数据
    async setTableList (skuNos) {
      if (skuNos) this.skuNos = skuNos
      const data = {
        delSaleAreaCodeList: this.salesArea.codes,
        skuNoList: this.skuNos
      }
      const res = await querySkuList4DelSaleAreaService(data, this.TableInfo.setLoading)
      if (res?.retData) {
        // 过滤掉已经存在的SKU
        const remainingList = this.TableInfo.list.filter(item => !this.skuNos.includes(item.skuNo))
        // 加入新关联的商品
        this.TableInfo.setList([...remainingList, ...res.retData])
      }
    },
    // 提交删除区域信息
    async submitDeleteAreaInfo () {
      const data = {
        delSaleAreaCodeList: this.salesArea.codes,
        skuNoList: this.TableInfo.getListAttrs(),
        launchReason: this.launchReason
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await commitDelSaleAreaService(data, loadingFn)
      if (res?.retStatus != '1') return
      // 无法提交商品信息处理
      if (res?.retData) {
        this.TableInfo.setColumns([ERROR_MSG_COL, ...this.TableInfo.columns])
        this.TableInfo.setList(res.retData)
        return this.$message.warning('存在禁止提交原因，无法提交单据')
      }
      this.$message.success('提交成功')
      this.$router.push({ name: 'chageFromManageList' })
    }
  }
}
</script>
<style lang="less" scoped>
.show-content {
  max-width: 400px;
  color: #85888e;
  font-size: 13px;
  line-height: 13px;
}
.delete-area-wrap {
  display: flex;
  align-items: center;
  .el-button {
    margin-left: 10px;
  }
}
</style>
